package com.my.study.net.transfer;

import com.my.study.io.StreamUtils;
import lombok.extern.slf4j.Slf4j;

import java.io.*;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;

/**
 * @author Carlos
 * @version 1.0
 * @Description 客户端
 *
 * 负责下载文件
 *
 * @date 2021/7/4 21:51
 **/
@Slf4j(topic = "c.FileDownloadClient")
public class FileDownloadClient {

    private static final String PATH_PARENT = "D:/file/";

    public static void main(String[] args) throws IOException {
        // 1.接收用户输入
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入下载的文件名：");
        String downloadFileName = scanner.next();
        log.debug("下载的文件名: {}", downloadFileName);

        // 2.连接服务端并发送下载文件名
        Socket socket = new Socket(InetAddress.getLocalHost(), 9999);
        OutputStream out = socket.getOutputStream();
        out.write(downloadFileName.getBytes());
        socket.shutdownOutput();


        // 3.接收文件数据
        BufferedInputStream bis = new BufferedInputStream(socket.getInputStream());
        byte[] bytes = StreamUtils.streamToByteArray(bis);

        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(PATH_PARENT + downloadFileName + "3.txt"));
        bos.write(bytes);
        log.debug("下载成功...");

        // 关闭
        bos.close();
        bis.close();
        out.close();
        socket.close();
        scanner.close();
    }

}
